<template>
  <div class="user-management">
    <div class="header">
      <h1>用户管理</h1>
      <button class="add-btn" @click="showAddModal = true">添加用户</button>
    </div>

    <!-- 统计信息 -->
    <div class="stats">
      <div class="stat-card">
        <div class="stat-number">{{ users.length }}</div>
        <div class="stat-label">总用户数</div>
      </div>
      <div class="stat-card">
        <div class="stat-number">{{ registeredUsers.length }}</div>
        <div class="stat-label">已注册用户</div>
      </div>
      <div class="stat-card">
        <div class="stat-number">{{ todayLogins }}</div>
        <div class="stat-label">今日登录</div>
      </div>
    </div>

    <!-- 用户列表 -->
    <div class="user-list">
      <div class="list-header">
        <h2>用户列表</h2>
        <div class="search-box">
          <input 
            type="text" 
            v-model="searchQuery" 
            placeholder="搜索手机号..."
            class="search-input"
          >
        </div>
      </div>

      <div class="table-container">
        <table class="user-table">
          <thead>
            <tr>
              <th>手机号</th>
              <th>注册状态</th>
              <th>注册时间</th>
              <th>最后登录</th>
              <th>登录次数</th>
              <th>状态</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="user in filteredUsers" :key="user.id">
              <td>{{ maskPhoneNumber(user.phoneNumber) }}</td>
              <td>
                <span :class="['status-badge', user.isRegistered ? 'registered' : 'unregistered']">
                  {{ user.isRegistered ? '已注册' : '未注册' }}
                </span>
              </td>
              <td>{{ formatDate(user.registrationTime) }}</td>
              <td>{{ formatDate(user.lastLoginTime) }}</td>
              <td>{{ user.loginCount }}</td>
              <td>
                <span :class="['status-badge', user.status]">
                  {{ getStatusText(user.status) }}
                </span>
              </td>
              <td>
                <button class="action-btn delete" @click="deleteUser(user.id)">
                  删除
                </button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 添加用户模态框 -->
    <div v-if="showAddModal" class="modal-overlay" @click="showAddModal = false">
      <div class="modal" @click.stop>
        <div class="modal-header">
          <h3>添加新用户</h3>
          <button class="close-btn" @click="showAddModal = false">×</button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label>手机号</label>
            <input 
              type="text" 
              v-model="newUser.phoneNumber" 
              placeholder="请输入手机号"
              class="form-input"
            >
          </div>
          <div class="form-group">
            <label>
              <input type="checkbox" v-model="newUser.isRegistered">
              已注册用户
            </label>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn secondary" @click="showAddModal = false">取消</button>
          <button class="btn primary" @click="addUser" :disabled="!isValidPhoneNumber">
            添加
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, computed, onMounted } from 'vue'
import axios from 'axios'

interface User {
  id: string
  phoneNumber: string
  isRegistered: boolean
  registrationTime: string
  lastLoginTime: string
  loginCount: number
  status: string
}

export default defineComponent({
  name: 'UserManagement',
  setup() {
    const users = ref<User[]>([])
    const searchQuery = ref('')
    const showAddModal = ref(false)
    const newUser = ref({
      phoneNumber: '',
      isRegistered: false
    })

    // 获取用户列表
    const fetchUsers = async () => {
      try {
        const response = await axios.get('http://localhost:3000/users/list')
        if (response.data.success) {
          users.value = response.data.users
        }
      } catch (error) {
        console.error('获取用户列表失败:', error)
        alert('获取用户列表失败')
      }
    }

    // 添加用户
    const addUser = async () => {
      if (!isValidPhoneNumber.value) {
        alert('请输入正确的手机号')
        return
      }

      try {
        const response = await axios.post('http://localhost:3000/users/login', {
          phoneNumber: newUser.value.phoneNumber
        })
        
        if (response.data.success) {
          alert('用户添加成功')
          showAddModal.value = false
          newUser.value = { phoneNumber: '', isRegistered: false }
          await fetchUsers()
        }
      } catch (error: any) {
        console.error('添加用户失败:', error)
        if (error.response?.data?.message) {
          alert(error.response.data.message)
        } else {
          alert('添加用户失败')
        }
      }
    }

    // 删除用户
    const deleteUser = async (userId: string) => {
      if (!confirm('确定要删除这个用户吗？')) {
        return
      }

      try {
        const response = await axios.delete(`http://localhost:3000/users/${userId}`)
        if (response.data.success) {
          alert('用户删除成功')
          await fetchUsers()
        }
      } catch (error) {
        console.error('删除用户失败:', error)
        alert('删除用户失败')
      }
    }

    // 计算属性
    const filteredUsers = computed(() => {
      if (!searchQuery.value) return users.value
      return users.value.filter(user => 
        user.phoneNumber.includes(searchQuery.value)
      )
    })

    const registeredUsers = computed(() => {
      return users.value.filter(user => user.isRegistered)
    })

    const todayLogins = computed(() => {
      const today = new Date().toDateString()
      return users.value.filter(user => {
        const loginDate = new Date(user.lastLoginTime).toDateString()
        return loginDate === today
      }).length
    })

    const isValidPhoneNumber = computed(() => {
      const phoneRegex = /^1[3-9]\d{9}$/
      return phoneRegex.test(newUser.value.phoneNumber)
    })

    // 工具函数
    const maskPhoneNumber = (phone: string) => {
      return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
    }

    const formatDate = (dateString: string) => {
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN')
    }

    const getStatusText = (status: string) => {
      const statusMap: Record<string, string> = {
        active: '正常',
        inactive: '非活跃',
        blocked: '已封禁'
      }
      return statusMap[status] || status
    }

    onMounted(() => {
      fetchUsers()
    })

    return {
      users,
      searchQuery,
      showAddModal,
      newUser,
      filteredUsers,
      registeredUsers,
      todayLogins,
      isValidPhoneNumber,
      addUser,
      deleteUser,
      maskPhoneNumber,
      formatDate,
      getStatusText
    }
  }
})
</script>

<style scoped>
.user-management {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.header h1 {
  margin: 0;
  color: #333;
}

.add-btn {
  background: #007AFF;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
}

.add-btn:hover {
  background: #0056CC;
}

/* 统计卡片 */
.stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.stat-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  text-align: center;
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #007AFF;
  margin-bottom: 8px;
}

.stat-label {
  color: #666;
  font-size: 14px;
}

/* 用户列表 */
.user-list {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.list-header {
  padding: 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.list-header h2 {
  margin: 0;
  color: #333;
}

.search-box {
  position: relative;
}

.search-input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  width: 200px;
  font-size: 14px;
}

.search-input:focus {
  outline: none;
  border-color: #007AFF;
}

/* 表格 */
.table-container {
  overflow-x: auto;
}

.user-table {
  width: 100%;
  border-collapse: collapse;
}

.user-table th,
.user-table td {
  padding: 12px 16px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.user-table th {
  background: #f8f9fa;
  font-weight: 600;
  color: #333;
}

.user-table tr:hover {
  background: #f8f9fa;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.registered {
  background: #d4edda;
  color: #155724;
}

.status-badge.unregistered {
  background: #f8d7da;
  color: #721c24;
}

.status-badge.active {
  background: #d1ecf1;
  color: #0c5460;
}

.status-badge.inactive {
  background: #fff3cd;
  color: #856404;
}

.status-badge.blocked {
  background: #f8d7da;
  color: #721c24;
}

.action-btn {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.action-btn.delete {
  background: #dc3545;
  color: white;
}

.action-btn.delete:hover {
  background: #c82333;
}

/* 模态框 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  padding: 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #666;
}

.modal-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #333;
  font-weight: 500;
}

.form-input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.form-input:focus {
  outline: none;
  border-color: #007AFF;
}

.modal-footer {
  padding: 20px;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.btn {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.btn.primary {
  background: #007AFF;
  color: white;
}

.btn.primary:hover:not(:disabled) {
  background: #0056CC;
}

.btn.primary:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.btn.secondary {
  background: #6c757d;
  color: white;
}

.btn.secondary:hover {
  background: #5a6268;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
  
  .stats {
    grid-template-columns: 1fr;
  }
  
  .list-header {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
  
  .search-input {
    width: 100%;
  }
  
  .user-table {
    font-size: 12px;
  }
  
  .user-table th,
  .user-table td {
    padding: 8px;
  }
}
</style> 